package com.accenture.portal.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.accenture.portal.model.Article;
import com.accenture.portal.model.User;
import com.accenture.portal.service.ArticleService;

/**
 * @author jun.m.wang
 * @
 */
@Controller
public class ArticleController {

	@Autowired
	private ArticleService articleService;
	
	protected Logger logger = Logger.getLogger(ArticleController.class);

	/**上传图片，用于后台增加和编辑文章
	 * @Title imageUpload
	 * @param request
	 * @param response
	 
	 */
	@RequestMapping("imageUpload.action")
	public void imageUpload(HttpServletRequest request,
			HttpServletResponse response) {
		String DirectoryName = "upload";//服务器保存图片目录
		try {
			ImageUploadUtil.ckeditor(request, response, DirectoryName);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**根据id获取文章
	 * @param article_id
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "content.action")
	public void getContent(@RequestParam("article_id") Integer article_id,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		Article articleChosen = articleService.getContent(article_id);
		JSONObject json = JSONObject.fromObject(articleChosen);
		String result = json.toString();
		
		try {
			response.getWriter().write(result);
			response.getWriter().flush();//清空缓冲区，完成写入
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**后台添加文章
	 * @param article
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "addArticle.action", method = RequestMethod.POST)
	public String addArticle(@ModelAttribute("article") Article article,
			HttpServletRequest request, HttpServletResponse response,
			Model model) throws UnsupportedEncodingException {
		articleService.addArticle(article);
		int number = (int) request.getSession().getAttribute("number");//获取当前页
		return "redirect:allByPage.action?number=" + number;//返回并刷新当前页
	}

	/**首页3条文章展示，局部刷新显示更多文章
	 * @param numI
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "readMore.action")
	public void readMoreArticle(@RequestParam("numI") int numI,HttpServletRequest request,
			HttpServletResponse response) {
		Integer user_id=((User)request.getSession().getAttribute("user")).getUser_id();//获取当前user_id
		List<Article> unreadArticle = articleService.getUnreadArticle(user_id,numI);//从数据库获取numI条数据

		JSONArray json = JSONArray.fromObject(unreadArticle);
		String result = json.toString();
		try {
			response.getWriter().write(result);
			response.getWriter().flush();//清空缓冲区，完成写入
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**首页标记为已读
	 * @param idStr
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "markMulti.action")
	public void markAsReadMulti(@RequestParam("idStr") String idStr,
	HttpServletRequest request, HttpServletResponse response, Model model) {
		Integer user_id=((User)request.getSession().getAttribute("user")).getUser_id();
		String markMulti[] = idStr.split(",");//包含article_id的字符串分割为数组
		articleService.markAsReadMulti(user_id, markMulti);
	}
	
	/**前台未读列表分页显示
	 * @param number
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "unreadList.action" ,method=RequestMethod.GET)
	public void getUnreadList(@RequestParam("number") int number,
			HttpServletRequest request,HttpServletResponse response, Model model) {
		Integer user_id=((User)request.getSession().getAttribute("user")).getUser_id();
		int page = 10;//一页显示数据条数
		int total = articleService.getUnreadCount(user_id);//总条数
		int count = total / page;
		if (total % page != 0) {
			count++;//总页数
		}
		
		if(count==0){ 
			count=1;//数据库没有数据时显示在总共1页
		}
		
		List<Article> unreadList = articleService.getUnreadList(user_id,(number - 1)* page, page);//获取当前页数据
		request.getSession().setAttribute("number", number);
		model.addAttribute("unreadList", unreadList);
		request.getSession().setAttribute("count", count);
		Map<String,Object> mapMulti=new HashMap<String, Object>();//封装为map发送到前台
		mapMulti.put("count",count);
		mapMulti.put("unreadList", unreadList);
		JSONObject json = JSONObject.fromObject(mapMulti);
		String result = json.toString();
		try {
			response.getWriter().write(result);
			response.getWriter().flush();//清空缓冲区，完成写入
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**逻辑删除文章
	 * @param article_id
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "deleteArticle.action", method = RequestMethod.GET)
	public String deleteArticle(@RequestParam("article_id") Integer article_id,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		articleService.deleteArticle(article_id);
		int number = (int) request.getSession().getAttribute("number");
		return "redirect:allByPage.action?number=" + number;//返回并刷新当前页
	}

	/**后台编辑文章功能
	 * @param article
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "editArticle.action", method = RequestMethod.POST)
	public String editArticle(@ModelAttribute Article article,
			HttpServletRequest request, HttpServletResponse response,
			Model model) throws UnsupportedEncodingException {
		article.setArticle_id((Integer)request.getSession().getAttribute("article_id"));//获取当前编辑的文章id
		articleService.editArticle(article);
		int number = (int) request.getSession().getAttribute("number");
		return "redirect:allByPage.action?number=" + number;//返回并刷新当前页
	}

	/**
	 * 后台分页显示文章列表
	 * @param number
	 * @param request
	 * @param model
	 */
	@RequestMapping(value = "allByPage.action")
	public String getAllByPage(@RequestParam("number") int number,
			HttpServletRequest request, Model model) {
		int page = 6;//每页显示条数
		int total = articleService.getTotalCount();//总条数
		int count = total / page;
		if (total % page != 0) {  
			count++;              //总页数
		}
		
		if(count==0){ 
			count=1;//数据库没有数据时显示在总共1页
		}
		
		if (number < 1) {//当前最小页数限制
			number = 1;
		} else if (number > count) {
			number = count;//当前最大页数限制
		}
		
		List<Article> articleList = articleService.getAllByPage((number - 1)
				* page, page);//取一页的数据
		request.getSession().setAttribute("number", number);
		model.addAttribute("articleList", articleList);
		request.getSession().setAttribute("count", count);

		return "allArticle";
	}

	/**跳转添加页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "toAdd.action", method = RequestMethod.GET)
	public String toAdd(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		return "addArticle";
	}

	/**跳转编辑页面
	 * @param article_id
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "toEdit.action", method = RequestMethod.GET)
	public String toEdit(@RequestParam("article_id") Integer article_id,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		Article article = articleService.getArticleById(article_id);
		request.getSession().setAttribute("article_id", article_id);
		model.addAttribute("articleLast", article);
		return "editArticle";
	}
}
